using System;
using Project.Utilities.Abstractions;

namespace Project.Utilities
{
    public class SecondaryStatPoints : ReactiveProperty<int>, IReadOnlySecondaryStatPoints
    {
        private readonly PrimaryStatPoints _primaryStatPoints;
        private readonly float _multiplier;
        private int _maxValue;

        public SecondaryStatPoints(PrimaryStatPoints primaryStatPoints, float multiplier) : base(0)
        {
            _primaryStatPoints = primaryStatPoints;
            _multiplier = multiplier;
            _maxValue = (int)(_primaryStatPoints.Value * _multiplier);

            ProtectedSetValueFunc = value => Math.Clamp(value, 0, MaxValue);

            _primaryStatPoints.ValueChanged += OnPrimaryStatPointsValueChanged;
        }

        public int MaxValue 
        { 
            get => _maxValue; 
            private set
            {
                if (_maxValue != value)
                {
                    _maxValue = value;

                    if (Value > _maxValue)
                        Value = _maxValue;

                    MaxValueChanged?.Invoke(value);

                }
            }
        }

        public event Action<int> MaxValueChanged;

        public void Dispose() =>
            _primaryStatPoints.ValueChanged += OnPrimaryStatPointsValueChanged;

        private void OnPrimaryStatPointsValueChanged(int newValue) =>
            MaxValue = (int)(newValue * _multiplier);
    }
}
